//
//  YPWebViewVC.m
//  WHISPER
//
//  Created by lanou3g on 15/12/19.
//  Copyright © 2015年 王艳苹. All rights reserved.
//

#import "YPWebViewVC.h"
#import "UIView+Extention.h"
#import "YPTopButton.h"
#import "YPHomePageVC.h"
#import  "UIImageView+WebCache.h"
#import "YPUser.h"
#import "YPWorldView.h"
#import "YSAVObject.h"
#import "YSpersonalConreoller.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "CollectModel.h"
#import "LYLoginViewController.h"
#define webUrl @"http://pianke.me/webview/"

static NSInteger world = 100;
@interface YPWebViewVC ()<UIWebViewDelegate>

@property (nonatomic,strong) UIWebView *detailView;
@property (nonatomic,strong) UIActivityIndicatorView *activityView;
@property (nonatomic,strong) YPWorldView *world;
@property (nonatomic,strong) UIAlertController *alert;
@end
@implementation YPWebViewVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadWebView];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [leftButton setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    [leftButton setFrame:CGRectMake(15, 10,30, 30)];
    [leftButton addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:leftButton];
    NSArray *typeArr = @[@"摄影",@"插画",@"话题",@"碎片",@"动态"];
    [self setNavagationBarButtonWithFlag:[typeArr containsObject:self.type]];
}

- (void)setNavagationBarButtonWithFlag:(BOOL)flag{
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    shareBtn.frame  = CGRectMake(self.view.width - 50,10, 30, 30);
    [shareBtn addTarget:self action:@selector(shareItemAction:) forControlEvents:UIControlEventTouchUpInside];
    [shareBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-fenxiang"] forState:UIControlStateNormal];
    [self.navigationController.navigationBar addSubview:shareBtn];
    
    YPTopButton *discussBtn = [[YPTopButton alloc]init];
    [discussBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-iconfontshoucang"] forState:UIControlStateNormal];
    [discussBtn addTarget:self action:@selector(discussItemAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:discussBtn];
    
    if (flag) {//如果是2个按键
        self.detailView.frame = CGRectMake(0,0, self.view.width, self.view.hight);
        discussBtn.frame = CGRectMake(CGRectGetMinX(shareBtn.frame) - 50, 10, 30, 30);
    }else{//3个按键
        UIButton *worldBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [worldBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-ziti-1"] forState:UIControlStateNormal];
        [worldBtn addTarget:self action:@selector(worldItemAction:) forControlEvents:UIControlEventTouchUpInside];
        worldBtn.frame = CGRectMake(CGRectGetMinX(shareBtn.frame) - 50,10, 30, 30);
        [self.navigationController.navigationBar addSubview:worldBtn];
        discussBtn.frame = CGRectMake(CGRectGetMinX(worldBtn.frame) - 50, 10, 30, 30);
        self.detailView.frame = CGRectMake(0,-44, self.view.width, self.view.hight+44);
    }
}
- (void)setUserView{
    UIView *back = [[UIView alloc]initWithFrame:CGRectMake(0,64, self.view.width, 60)];
    back.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:back];
    UIImageView *userImage = [[UIImageView alloc]initWithFrame:CGRectMake(20,5, 50, 50)];
    userImage.layer.masksToBounds = YES;
    userImage.layer.cornerRadius = 25;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    userImage.userInteractionEnabled = YES;
    [userImage sd_setImageWithURL:[NSURL URLWithString:self.user.icon] placeholderImage:[UIImage imageNamed:@"1"]];
    [back addSubview:userImage];
    UILabel *userName = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(userImage.frame) + 10, 10,self.view.width - CGRectGetMaxX(userImage.frame) - 30, 40)];
    userName.text = self.user.uname;
    [back addGestureRecognizer:tap];
    [back addSubview:userName];
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(userName.frame) + 9,self.view.width - 40, 1)];
    lable.backgroundColor = [UIColor grayColor];
    [back addSubview:lable];
    self.detailView.frame = CGRectMake(0,16,self.view.width, self.view.hight);
}
- (void)tapAction:(UITapGestureRecognizer*)sender{
    YSpersonalConreoller *person = [[YSpersonalConreoller alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:person];
    person.uid = self.user.uid;
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}
- (void)loadWebView{
    self.detailView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0,self.view.width, self.view.hight)];
    [self.view addSubview:_detailView];
    NSURL *url = [NSURL URLWithString:self.tingID];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.detailView loadRequest:request];
    self.detailView.delegate = self;
}
- (void)leftAction:(UIButton*)sender{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
//收藏
- (void)discussItemAction:(UIBarButtonItem*)sender{
    NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"login"];
    if (str == nil || [str isEqualToString:@"nlogin"]) {
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        [controller addAction:action];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LYLoginViewController *conreoller = [[LYLoginViewController alloc]init];
            [self.navigationController presentViewController:conreoller animated:YES completion:nil];
        }];
        [controller addAction:action1];
        [self presentViewController:controller animated:YES completion:nil];
    }else{
        [[YSAVObject shareAVObject] isCollectionWithUrl:self.tingID userName:[[NSUserDefaults standardUserDefaults] objectForKey:@"userName"]block:^(BOOL isCollection) {
            NSString *str = @"";
            if (isCollection) { //收藏过
                // 取消收藏
                str = @"已收藏";
            } else {
                [[YSAVObject shareAVObject] inseartToAvObjectWithTitle:self.shareTitle Url:self.tingID userName:[[NSUserDefaults standardUserDefaults]objectForKey:@"userName"]];
                str = @"收藏成功";
            }
            UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [controller addAction:action];
            [self presentViewController:controller animated:YES completion:nil];
        }];
    }
}
- (void)worldItemAction:(UIBarButtonItem*)sender{
    if (!_world.isOpen) {
    _world = [[YPWorldView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _world.y = 0;
    _world.isOpen = YES;
    [_world.little addTarget:self action:@selector(littleAction:) forControlEvents:UIControlEventTouchUpInside];
    [_world.big addTarget:self action:@selector(bigAction:) forControlEvents:UIControlEventTouchUpInside];
    [_world.white addTarget:self action:@selector(whiteAction:) forControlEvents:UIControlEventTouchUpInside];
    [_world.black addTarget:self action:@selector(blackAction:) forControlEvents:UIControlEventTouchUpInside];
    }else{
        [self.world dismiss];
        _world.isOpen = NO;
    }
}

- (void)littleAction:(UIButton*)sender{
    world -= 10;
    self.world.big.enabled = YES;
    if (world >= 80) {
        NSString *str = [NSString stringWithFormat:@"%ld%%",(long)world];
        NSString *js = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%@'",str];
        [self.detailView stringByEvaluatingJavaScriptFromString:js];
    }else{
        self.world.little.enabled = NO;
    }
}

- (void)bigAction:(UIButton*)sender{
    world += 10;
    self.world.little.enabled = YES;
    if (world <= 120) {
        NSString *str = [NSString stringWithFormat:@"%ld%%",(long)world];
        NSString *js = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%@'",str];
        [self.detailView stringByEvaluatingJavaScriptFromString:js];
    }else{
        self.world.big.enabled = NO;
    }
}
- (void)whiteAction:(UIButton*)sender{
    [self.detailView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'black'"];
    [self.detailView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#FFFFFF'"];
}
- (void)blackAction:(UIButton*)sender{
    [self.detailView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'gray'"];
    [self.detailView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#2E2E2E'"];
}
- (void)shareItemAction:(UIBarButtonItem*)sender{
    //1、创建分享参数
    NSArray* imageArray = @[self.shareImage];
    NSString *str = [NSString stringWithFormat:@"%@:%@",self.shareTitle,self.tingID];
    if (imageArray) {
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:str
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://mob.com"]
                                          title:@"分享标题"
                                           type:SSDKContentTypeAuto];
        [ShareSDK showShareActionSheet:nil
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:{
                               self.alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"分享成功" preferredStyle:UIAlertControllerStyleAlert];        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                               [self.alert addAction:action];
                               [self presentViewController:self.alert animated:YES completion:nil];
                               break;
                           }
                           case SSDKResponseStateFail:{
                               NSString *err = [NSString stringWithFormat:@"分享失败：%@",error];
                               self.alert = [UIAlertController alertControllerWithTitle:@"提示" message:err preferredStyle:UIAlertControllerStyleAlert];        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                               [self.alert addAction:action];
                               [self presentViewController:self.alert animated:YES completion:nil];

                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    if ([self.type isEqualToString:@"碎片"] || [self.type isEqualToString:@"动态"] ) {
        [self setUserView];
    }
    [self.activityView stopAnimating];
    UIView *view = [self.view viewWithTag:500];
    [view removeFromSuperview];
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    UIView *blackView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.alpha = 0.5;
    blackView.tag = 500;
    [self.view addSubview:blackView];
    self.activityView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 32, 32)];
    self.activityView.center = blackView.center;
    self.activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [blackView addSubview:_activityView];
    [self.activityView startAnimating];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [self.activityView stopAnimating];
    UIView *view = [self.view viewWithTag:500];
    [view removeFromSuperview];
    UIImageView *image = [[UIImageView alloc] initWithFrame:self.view.frame];
    image.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:image];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
